package com.zzyq.pc.common.plugin.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.CodeMsg;
import com.zzyq.pc.utils.HttpUtils;

/**
 * 
 * <p>
 * 
 * @Title: PermissionFilter.java
 * @Description: 权限校验过滤器
 * @author: Sywd丶吴迪
 * @date: 2017年8月30日 上午10:26:13
 * @version V1.0
 *          <p>
 */
public class PermissionFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        try {
            if (null == mappedValue) {
                return false;
            }
            // 先判断带参数的权限判断
            Subject subject = getSubject(request, response);
            if (null != mappedValue) {
                String[] arra = (String[]) mappedValue;
                for (String permission : arra) {
                    if (subject.isPermitted(permission)) {
                        return Boolean.TRUE;
                    }
                }
            }
            HttpServletRequest httpRequest = ((HttpServletRequest) request);
            String uri = httpRequest.getRequestURI();// 获取URI
            String basePath = httpRequest.getContextPath();// 获取basePath
            if (null != uri && uri.startsWith(basePath)) {
                uri = uri.replaceFirst(basePath, "");
            }
            if (subject.isPermitted(uri)) {
                return Boolean.TRUE;
            }
            if (HttpUtils.isAjax(request)) {// AJAX请求
                String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_LOGIN_REQUEST,
                        CodeMsg.MSG_LOGIN_REQUEST, null);
                HttpUtils.out(response, str);
            } else {
                WebUtils.issueRedirect(request, response, HttpUtils.LOGIN_URL);
//                request.getRequestDispatcher(HttpUtils.LOGIN_URL).forward(request, response);
            }
        } catch (Exception e) {

        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (null == subject.getPrincipal()) {// 表示没有登录，重定向到登录页面
            saveRequest(request);
            request.getRequestDispatcher(HttpUtils.LOGIN_URL).forward(request, response);
        } else {
            String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_POWER_ERROR,
                    CodeMsg.MSG_POWER_ERROR, null);
            HttpUtils.out(response, str);
        }
        return false;
    }

}
